const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { generateSudoku, isValid, getSolution, getHint } = require('./utils/sudokuGenerator');

const app = express();
const port = 5001;

// 更新CORS配置
app.use(cors({
  origin: 'http://192.168.3.31:3001',
  methods: ['GET', 'POST'],
  allowedHeaders: ['Content-Type']
}));

app.use(bodyParser.json());

// 生成新的数独游戏
app.get('/api/new-game', (req, res) => {
  const { difficulty } = req.query;
  const board = generateSudoku(difficulty);
  res.json({ board });
});

// 验证数独答案
app.post('/api/validate', (req, res) => {
  const { board } = req.body;
  
  // 验证每个单元格
  for (let i = 0; i < 9; i++) {
    for (let j = 0; j < 9; j++) {
      if (board[i][j] === 0) {
        return res.json({ valid: false, message: '还有空格未填写' });
      }
      
      // 临时移除当前数字进行验证
      const temp = board[i][j];
      board[i][j] = 0;
      if (!isValid(board, i, j, temp)) {
        return res.json({ valid: false, message: '答案不正确' });
      }
      board[i][j] = temp;
    }
  }
  
  res.json({ valid: true, message: '恭喜！答案正确！' });
});

// 添加获取提示的路由
app.post('/api/hint', (req, res) => {
  const { board, remainingHints } = req.body;
  
  if (remainingHints <= 0) {
    return res.json({ 
      error: true, 
      message: '提示次数已用完' 
    });
  }

  // 获取完整解决方案
  const solution = getSolution(board);
  
  // 获取一个提示
  const hint = getHint(board, solution);
  
  if (!hint) {
    return res.json({ 
      error: true, 
      message: '当前没有可用的提示' 
    });
  }

  res.json({ 
    hint,
    remainingHints: remainingHints - 1
  });
});

// 添加错误处理中间件
app.use((err, req, res, next) => {
  console.error(err.stack);
  res.status(500).json({ error: '服务器内部错误' });
});

app.listen(port, '0.0.0.0', () => {
  console.log(`服务器运行在 http://localhost:${port}`);
}); 